const BaseIpcHandler = require('../BaseIpcHandler');
const ELECTRON_ENV = process.env.ELECTRON_ENV;

let BrowserWindow = null;
if (ELECTRON_ENV) {
    BrowserWindow = require('electron').BrowserWindow;
}

class ToggleConsoleHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log('>> ToggleConsoleHandler params = ', params);

        // 业务逻辑
        let result = { code: -2, msg: 'Not in Electron Environment!' };

        if (ELECTRON_ENV && BrowserWindow) {
            const mainWindow = BrowserWindow.getFocusedWindow(); // 获取主窗口实例
            if (mainWindow) {
                let opened = mainWindow.webContents.isDevToolsOpened();
                if (opened) {
                    mainWindow.webContents.closeDevTools();
                } else {
                    mainWindow.webContents.openDevTools();
                }
                result = { code: 0, msg: `DevTools ${opened ? 'Closed' : 'Opened'}` };
            } else {
                result = { code: -1, msg: 'Main window not found' };
            }
        }

        // 返回结果
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = ToggleConsoleHandler;
